//
// Created by wangyg98 on 2025/3/30.
//

#include "player.h"
#include "put_image.h"
#include "constants.h"

Player::Player(const std::string& path, int num, int interval): Character(path, "player", num, interval) {

    //加载玩家角色阴影
    loadimage(&img_player_shadow, _T("D:\\Clion Project\\TeyvatSurvivor\\img\\shadow_player.png"));
}

void Player::ProcessEvent(const ExMessage &msg) {
    if (msg.message == WM_KEYDOWN) {
        switch (msg.vkcode) {
            case VK_UP:
                is_move_up = true;
                break;
            case VK_DOWN:
                is_move_down = true;
                break;
            case VK_LEFT:
                is_move_left = true;
                break;
            case VK_RIGHT:
                is_move_right = true;
        }
    }
    else if (msg.message == WM_KEYUP) {
        switch (msg.vkcode) {
            case VK_UP:
                is_move_up = false;
                break;
            case VK_DOWN:
                is_move_down = false;
                break;
            case VK_LEFT:
                is_move_left = false;
                break;
            case VK_RIGHT:
                is_move_right = false;
        }
    }
}

void Player::Move() {
    dir_x = is_move_right - is_move_left;
    dir_y = is_move_down - is_move_up;
    double len_dir = sqrt(dir_x*dir_x + dir_y*dir_y);
    if(len_dir!=0){
        double normalized_x = dir_x / len_dir;
        double normalized_y = dir_y / len_dir;
        player_pos.x += PLAYER_SPEED * normalized_x;
        player_pos.y += PLAYER_SPEED * normalized_y;
    }

    if(player_pos.x < 0)    player_pos.x = 0;
    if(player_pos.y < 0)    player_pos.y = 0;
    if(player_pos.x + PLAYER_WIDTH > g_window_width)    player_pos.x = g_window_width - PLAYER_WIDTH;
    if(player_pos.y + PLAYER_HEIGHT > g_window_hight)    player_pos.y = g_window_hight - PLAYER_HEIGHT;
}

void Player::Draw(int delta) {
    int pos_shadow_x = player_pos.x + (PLAYER_WIDTH/2 - SHADOW_WIDTH/2);
    int pos_shadow_y = player_pos.y + PLAYER_HEIGHT - 8;
    put_image_alpha(pos_shadow_x, pos_shadow_y, &img_player_shadow);

    this->SetFacingLeft(dir_x);
    this->Play(player_pos.x, player_pos.y, delta);
}

const POINT &Player::getPlayerPos() const {
    return player_pos;
}

const int Player::getPlayerWidth() const {
    return PLAYER_WIDTH;
}

const int Player::getPlayerHeight() const {
    return PLAYER_HEIGHT;
}
